package javbot;


import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.swing.JButton;

import javbot.command.ICommand;

public class RobotRunner {
	
	private static RobotThread rt;
	private static JButton runButton = null;

	public static void runCommandList(ICommand[] commandList) {
		if (isRunning()) {
			System.out.println("Script running already. Please wait.");
		} else {
			rt = new RobotThread(commandList, runButton);
			rt.start();			
		}
	}
	
	public static void stopRunning() {
		rt.expireThread();
		GlobalClass.cPanel.output("***** Script Aborted *****\n");	
	}
	
	public static boolean isRunning() {
		if (rt != null)
			return rt.isAlive();
		else
			return false;
	}
	
	public static void setRunButton(JButton runButton) {
		RobotRunner.runButton = runButton;
	}		
}	

class RobotThread extends Thread {
	
	private ICommand[] list;
	private JButton runButton;
	private boolean run;
	
	public RobotThread(ICommand[] commandList, JButton runButton) {
		list = commandList;
		this.runButton = runButton;
	}
	
	public void expireThread() {
		run = false;
		interrupt();
	}
	
	public void run() {	
		
		if (runButton != null)
			runButton.setText("Stop");
				
		GlobalClass.cPanel.output("***** Running Script *****\n" +
				(new SimpleDateFormat()).format(Calendar.getInstance().getTime())+ " \n");
		
		run = true;
		while (run) {
		
			for (int i=0; i < list.length; i++) {
				GlobalClass.cPanel.output(i + 1 + ": " + list[i] + "\n");
				list[i].execute();
			}
			
			if (GlobalClass.repeat == -1) break;
			else if(GlobalClass.repeat > 0) {
				GlobalClass.cPanel.output("Waiting " + GlobalClass.repeat + " seconds");
				try {
					Thread.sleep(1000*GlobalClass.repeat);
				} catch (InterruptedException e) {
					break;
				}
			}
		}
		
		if (run)
			GlobalClass.cPanel.output("***** Finished Script *****\n\n");
		
		if (runButton != null)
			runButton.setText("Run");	
	}
}
